import { _decorator, Component, instantiate, Node, Prefab, SpriteFrame } from 'cc';
import GameEventMgr, { GameEvent } from '../../Model/GameEventMgr';
import { LevelUpCom } from '../../Entity/Component/LevelUpCom';
import { SkillButtonItem } from './SkillButtonItem';
import { UnitPlanetBase } from '../../Entity/UnitPlanetBase';
import { SkillData } from '../../Util/Global';
import AssetsMgr from '../../Model/AssetsMgr';
const { ccclass, property } = _decorator;

@ccclass('SkillViewUI')
export class SkillViewUI extends Component {

    @property({ type: Node })
    public content: Node = null;
    @property(Prefab)
    public itemPrefab: Prefab = null;

    public unit: UnitPlanetBase = null;
    public target_levelCom: LevelUpCom = null;
    start() {

        GameEventMgr.Register(this, GameEvent.GameStart, this.RefreshViewUI.bind(this));
        GameEventMgr.Register(this, GameEvent.PlayerDataChange, this.RefreshViewUI.bind(this));

    }

    update(dt) {

        this.content.setPosition(0, 0);
    }

    RefreshViewUI() {
        if (this.target_levelCom == null) {
            return;
        }

        let children = this.content.children;
        let skillCount = this.target_levelCom.skillMap.size;
        let index = 0;

        // 删除多余的 child
        while (children.length > skillCount) {
            let lastChild = children[children.length - 1];
            this.content.removeChild(lastChild); // 从 content 中移除多余的 child
            lastChild.destroy(); // 销毁多余的 child
        }

        // 遍历 skillLevelMap
        for (let [k, v] of this.target_levelCom.skillMap) {
            let child = children[index];

            // 如果 child 不存在，则创建一个新的 child
            if (child == null) {
                child = instantiate(this.itemPrefab);
                this.content.addChild(child); // 将新创建的 child 添加到 content 中
            }

            // 获取或添加 SkillButtonItem 组件
            let skillItem = child.getComponent(SkillButtonItem);

            // 更新 skillItem 的数据
            skillItem.levelCom = this.target_levelCom;
            skillItem.skillType = k;

            let skillData = SkillData.SkillMap.get(k);

            AssetsMgr.getRes(skillData.iconPath, SpriteFrame, (sp) => {
                skillItem.icon.spriteFrame = sp;
            });

            index++;
        }
    }
}

